//
//  CarTypeViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "CarTypeViewController.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "CarTypeCell.h"
#import "ChoiceCarTypeVC.h"
#import "Common.h"
#import <UIImageView+WebCache.h>
#import "WKProgressHUD.h"

@interface CarTypeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UIView *nullView;
@property (nonatomic,strong) WKProgressHUD *hud;


@end

@implementation CarTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [self initNullView];
    
    self.dataArray = [NSMutableArray array];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"常用车型管理"];
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = GrayColor;
    

    [self initSourceData];
    
    [self initTableView];
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

}

-(void)initNullView
{
    self.nullView = [[UIView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight)];
    self.nullView.backgroundColor = GrayColor;
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMidX(self.view.frame) - 23, 95, 46, 52)];
    imageV.image = [UIImage imageNamed:@"no_car"];
    
    [self.nullView addSubview:imageV];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageV.frame) + 14, screenWidth, 20)];
    label.textColor = BtnTitleColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = Font(13);
    label.text = @"暂时没有常用车型";
    
    [self.nullView addSubview:label];
    

}

//获取网络数据
-(void)initSourceData
{
    
    [Common requestWithUrlString:user_vehicle_list contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        if (self.dataArray.count > 0) {
            
            [self.tableView reloadData];
            
            [self.nullView removeFromSuperview];
            
        } else {
            
            [self.tableView addSubview:self.nullView];
            
        }
        
    
    } failed:^(NSString *errorMsg) {
    
//        [WKProgressHUD popMessage:@"保存成功" inView:self.view duration:1.5 animated:YES];
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
    }];
    
    
}

-(void)initTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    [self.view addSubview:self.tableView];
    
    
   
}


#pragma mark UITabelViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellString = @"carTypeCell";
    
    CarTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
    if (!cell) {
        cell = [[CarTypeCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellString
                ];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSString *brandString = self.dataArray[indexPath.row][@"brandName"];
    NSString *imgString = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"brandLogo"]];
    
//  //
    [cell.logoImageV sd_setImageWithURL:[NSURL URLWithString:imgString] placeholderImage:[UIImage imageNamed:@"car_style1"]];
    
    cell.brandLabel.text = brandString;
    
    cell.typeLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"vehicleName"]];
    
    cell.deleteButton.tag = indexPath.row + 300;
    
    [cell.deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50 *kHeight;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];

}

-(void)addButton
{
    ChoiceCarTypeVC *choiceVC = [[ChoiceCarTypeVC alloc]init];
    
    choiceVC.callBack = ^(NSString *str1,NSString *str2 ,NSString *str3,NSString *str4){
        
       
    };
    
    choiceVC.callBackId = ^(NSString *str1,NSString *str2 ,NSString *str3,NSString *str4){
       
        NSDictionary *dic = @{@"vehicleid":str1,
                              @"brandid":str2,
                              @"brandname":str4,
                              @"vehiclename":str3
                              };
        
        
        Common *c = [[Common alloc]init];
        
        
        [c afPostRequestWithUrlString:user_vehicle_create parms:dic finishedBlock:^(id responseObj) {
            
            NSDictionary *dicionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            
            
            if ([dicionary[@"success"] boolValue]) {
                
                [self initSourceData];
            }
            
        } failedBlock:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];

        
        
    };

    
    [self.navigationController pushViewController:choiceVC animated:YES];
}



-(void)deleteButtonAction:(UIButton *)sender
{
    
    [self.tableView beginUpdates];
    
    NSString *urlString = [NSString stringWithFormat:@"%@uservehicle/delete",Main_interface];
    
    NSDictionary *dic = @{@"id":self.dataArray[sender.tag - 300][@"id"]
                         };
    

    Common *c = [[Common alloc]init];
    
    
    [c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dicionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        
        if ([dicionary[@"success"] boolValue]) {
            
          
//        dicionary[@"message"] 提示删除是否成功
            
#warning 可以添加提示框
            [self.dataArray removeObjectAtIndex:sender.tag - 300];
            
            NSIndexPath *deletePath = [NSIndexPath indexPathForRow:sender.tag - 300 inSection:0];
            
            //删除一行
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:deletePath] withRowAnimation:UITableViewRowAnimationLeft];
            
            //删除一个section
//            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sender.tag - 300] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];

            [self initSourceData];
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    

    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
